#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
#include <iostream>
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;

typedef websocketpp::server<websocketpp::config::asio> server;

// 定义消息处理器
void on_message(server *s, websocketpp::connection_hdl hdl, server::message_ptr msg)
{
    std::cout << "Received: " << msg->get_payload() << std::endl;

    // 回复相同消息（回声）
    try
    {
        s->send(hdl, msg->get_payload(), msg->get_opcode());
    }
    catch (const websocketpp::exception &e)
    {
        std::cerr << "Send failed: " << e.what() << std::endl;
    }
}

int main()
{
    server ws_server;

    // 初始化 ASIO
    ws_server.init_asio();

    // 设置消息处理器
    ws_server.set_message_handler(bind(&on_message, &ws_server, ::_1, ::_2));

    // 监听端口 9002
    ws_server.listen(9002);

    // 开始接受连接
    ws_server.start_accept();

    std::cout << "Server started on port 9002" << std::endl;

    // 运行事件循环
    ws_server.run();

    return 0;
}